<template>
<!-- 参合缴费管理 -->
  <div class="payment-container">
    <!-- 搜索栏 -->
    <div class="search-container">
      <el-form :model="searchForm" class="search-form" label-width="80px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="家庭ID">
              <el-input
                v-model.number="searchForm.familyId"
                placeholder="请输入家庭ID"
                clearable
              />
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="缴费年度">
              <el-input
                v-model.number="searchForm.year"
                placeholder="请输入缴费年度"
                clearable
              />
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="缴费人姓名">
              <el-input
                v-model="searchForm.payerName"
                placeholder="请输入缴费人姓名"
                clearable
              />
            </el-form-item>
          </el-col>
          
          <!-- <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="缴费方式">
              <el-select
                v-model="searchForm.paymentMethod"
                placeholder="请选择缴费方式"
                clearable
              >
                <el-option label="现金" value="现金"></el-option>
                <el-option label="银行卡" value="银行卡"></el-option>
                <el-option label="微信" value="微信"></el-option>
                <el-option label="支付宝" value="支付宝"></el-option>
                <el-option label="其他" value="其他"></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          
          <el-col :xs="24" :sm="24" :md="24" :lg="6" class="search-buttons">
            <el-button type="primary" @click="handleSearch">
              <i class="el-icon-search"></i> 搜索
            </el-button>
            <el-button @click="resetSearch">
              <i class="el-icon-refresh"></i> 重置
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="operation-buttons">
      <el-button type="primary" @click="handleAdd">
        <i class="el-icon-plus"></i> 新增缴费记录
      </el-button>
    </div>

    <!-- 表格 -->
    <div class="table-container">
      <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
        element-loading-text="数据加载中..."
        :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
      >
        <el-table-column type="selection" width="55" align="center" />
        
        <el-table-column prop="paymentId" label="缴费记录ID" width="120" align="center" />
        
        <el-table-column prop="familyId" label="家庭ID" width="100" align="center" />
        
        <el-table-column prop="year" label="缴费年度" width="100" align="center" />
        
        <el-table-column prop="payerName" label="缴费人姓名" width="120" align="center" />
        
        <el-table-column prop="payerIdCard" label="身份证号" width="180" align="center">
          <template #default="{ row }">
            <span class="ellipsis" :title="row.payerIdCard">{{ row.payerIdCard }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="totalAmount" label="缴费金额(元)" width="120" align="center">
          <template #default="{ row }">
            {{ row.totalAmount ? row.totalAmount.toLocaleString() : '0' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="paymentTime" label="缴费时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.paymentTime) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="operatorName" label="操作员" width="100" align="center" />
        
        <el-table-column prop="invoiceNumber" label="发票号码" width="140" align="center">
          <template #default="{ row }">
            <span class="ellipsis" :title="row.invoiceNumber">{{ row.invoiceNumber }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="paymentMethod" label="缴费方式" width="100" align="center" />
        
        <el-table-column prop="createTime" label="创建时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.createTime, 'YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        
        <el-table-column prop="remark" label="备注" width="180" align="center">
          <template #default="{ row }">
            <span class="ellipsis" :title="row.remark || '-'" v-if="row.remark">{{ row.remark }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="mini" type="primary" plain @click="handleEdit(row)">
              <i class="el-icon-edit"></i> 编辑
            </el-button>
            <el-button size="mini" type="danger" plain @click="handleDelete(row)">
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        />
      </div>
    </div>

    <!-- 新增家庭选择弹窗 -->
    <el-dialog
      v-model="familySelectVisible"
      title="选择家庭及成员"
      width="500px"
      @close="handleFamilySelectClose"
    >
      <el-form :model="familyForm" label-width="80px">
        <el-form-item label="家庭ID">
          <el-input
            v-model.number="familyForm.familyId"
            placeholder="请输入家庭ID"
            clearable
            @blur="fetchFamilyMembers"
          />
        </el-form-item>
        
        <el-form-item label="户主姓名">
          <el-select
            v-model="familyForm.headOfHousehold"
            placeholder="请选择户主"
            clearable
            :disabled="!familyMembers || familyMembers.length === 0"
            @change="fetchIdCardByFamilyIdAndName"
          >
            <el-option 
              v-for="name in familyMembers" 
              :key="name" 
              :label="name" 
              :value="name"
            ></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="家庭成员">
          <el-checkbox-group
            v-model="selectedNames"
            v-if="familyMembers.length > 0"
          >
            <el-checkbox
              v-for="name in familyMembers"
              :key="name"
              :label="name"
            ></el-checkbox>
          </el-checkbox-group>
          <div v-else>请输入家庭ID查询成员</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="familySelectVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmFamilySelection">确认选择</el-button>
      </template>
    </el-dialog>

    <!-- 新增/编辑对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="700px" 
      :close-on-click-modal="false"
      :before-close="resetForm"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="家庭ID" prop="familyId">
              <el-input 
                type="number" 
                v-model.number="formData.familyId" 
                placeholder="自动填充"
                disabled
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="缴费年度" prop="year">
              <el-input 
                type="number" 
                v-model.number="formData.year" 
                placeholder="自动填充"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="缴费人姓名" prop="payerName">
              <el-input 
                v-model="formData.payerName" 
                placeholder="自动填充"
                disabled
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="身份证号" prop="payerIdCard">
              <el-input 
                v-model="formData.payerIdCard" 
                placeholder="自动填充"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="缴费金额" prop="totalAmount">
              <el-input 
                type="number" 
                step="0.01" 
                v-model.number="formData.totalAmount" 
                placeholder="自动计算"
                disabled
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="缴费时间" prop="paymentTime">
              <el-date-picker
                v-model="formData.paymentTime"
                type="datetime"
                placeholder="请选择缴费时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="操作员ID" prop="operatorId">
              <el-input 
                type="number" 
                v-model.number="formData.operatorId" 
                placeholder="请输入操作员ID"
                clearable
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="操作员姓名" prop="operatorName">
              <el-input 
                v-model="formData.operatorName" 
                placeholder="请输入操作员姓名"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发票号码" prop="invoiceNumber">
              <el-input 
                v-model="formData.invoiceNumber" 
                placeholder="请输入发票号码"
                clearable
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="缴费方式" prop="paymentMethod">
              <el-select
                v-model="formData.paymentMethod"
                placeholder="请选择缴费方式"
                clearable
              >
                <el-option label="现金" value="现金"></el-option>
                <el-option label="银行卡" value="银行卡"></el-option>
                <el-option label="微信" value="微信"></el-option>
                <el-option label="支付宝" value="支付宝"></el-option>
                <el-option label="其他" value="其他"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">
            <i class="el-icon-close"></i> 取消
          </el-button>
          <el-button type="primary" @click="submitForm">
            <i class="el-icon-check"></i> 确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request';
import { formatDate } from '@/utils/date';

export default {
  name: 'FamilyPaymentManagement',
  data() {
    return {
      // 搜索表单
      searchForm: {
        familyId: null,
        year: null,
        payerName: '',
        paymentMethod: ''
      },
      
      // 表格数据
      tableData: [],
      loading: false,
      
      // 分页配置
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      
      // 对话框配置
      dialogVisible: false,
      dialogTitle: '新增缴费记录',
      familySelectVisible: false, // 家庭选择弹窗可见性
      
      // 家庭选择表单
      familyForm: {
        familyId: null,
        headOfHousehold: '' // 新增户主姓名
      },
      familyMembers: [], // 家庭成员列表
      selectedNames: [], // 选中的成员姓名
      feeAmount: null, // 当前年度缴费标准
      
      // 表单数据
      formData: {
        paymentId: null,
        familyId: null,
        year: null,
        payerName: '', // 缴费人姓名（户主）
        payerIdCard: '',
        totalAmount: null,
        paymentTime: null,
        operatorId: null,
        operatorName: '',
        invoiceNumber: '',
        paymentMethod: '',
        remark: '',
        nameList: [] // 参合人员名称列表
      },
      
      // 表单验证规则
      formRules: {
        familyId: [
          { required: true, message: '请选择家庭', trigger: 'blur' }
        ],
        year: [
          { required: true, message: '请输入缴费年度', trigger: 'blur' },
          { type: 'number', message: '请输入数字', trigger: 'blur' },
          { validator: (rule, value, callback) => {
              if (value && (value < 2000 || value > new Date().getFullYear() + 1)) {
                callback(new Error('缴费年度应在2000年至当前年份+1之间'));
              } else {
                callback();
              }
            }, trigger: 'blur' }
        ],
        payerName: [
          { required: true, message: '请选择户主作为缴费人', trigger: 'blur' }
        ],
        payerIdCard: [
          { required: true, message: '身份证号不能为空', trigger: 'blur' },
          { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号格式不正确', trigger: 'blur' }
        ],
        totalAmount: [
          { required: true, message: '缴费金额不能为空', trigger: 'blur' },
          { type: 'number', message: '请输入数字', trigger: 'blur' },
          { validator: (rule, value, callback) => {
              if (value && value <= 0) {
                callback(new Error('缴费金额必须大于0'));
              } else {
                callback();
              }
            }, trigger: 'blur' }
        ],
        paymentTime: [
          { required: true, message: '请选择缴费时间', trigger: 'change' }
        ],
        operatorId: [
          { required: true, message: '请输入操作员ID', trigger: 'blur' },
          { type: 'number', message: '请输入数字', trigger: 'blur' }
        ],
        operatorName: [
          { required: true, message: '请输入操作员姓名', trigger: 'blur' },
          { min: 2, message: '操作员姓名至少2个字符', trigger: 'blur' }
        ],
        paymentMethod: [
          { required: true, message: '请选择缴费方式', trigger: 'change' }
        ]
      }
    };
  },
  
  methods: {
    // 格式化日期
    formatDate(date, format = 'YYYY-MM-DD') {
      return formatDate(date, format);
    },
    
    // 获取数据列表
    fetchData() {
      this.loading = true;
      request.get('/familyPayment/list', {
        params: {
          current: this.pagination.currentPage,
          size: this.pagination.pageSize,
          ...this.searchForm
        }
      })
        .then(res => {
          if (res.code === 200) {
            this.tableData = res.data.records;
            this.pagination.total = res.data.total;
          } else {
            this.$message.error(res.message || '获取缴费记录列表失败');
          }
        })
        .catch(err => {
          console.error('获取缴费记录列表失败:', err);
          this.$message.error('加载缴费记录列表失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 搜索处理
    handleSearch() {
      this.pagination.currentPage = 1;
      this.fetchData();
    },
    
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        familyId: null,
        year: null,
        payerName: '',
        paymentMethod: ''
      };
      this.handleSearch();
    },
    
    // 分页大小变更
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.fetchData();
    },
    
    // 当前页变更
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.fetchData();
    },
    
    // 新增缴费记录
    handleAdd() {
      this.resetForm();
      this.familySelectVisible = true; // 打开家庭选择弹窗
    },
    
    // 获取家庭成员姓名
    fetchFamilyMembers() {
      if (this.familyForm.familyId) {
        request.get(`/familyPayment/getNamesByFamilyId/${this.familyForm.familyId}`)
          .then(res => {
            if (res.code === 200) {
              this.familyMembers = res.data;
              this.selectedNames = []; // 清空之前的选择
              this.familyForm.headOfHousehold = ''; // 清空户主选择
              this.formData.payerIdCard = ''; // 清空身份证号
            } else {
              this.$message.error(res.message);
              this.familyMembers = [];
            }
          })
          .catch(err => {
            this.$message.error('获取家庭成员失败，请检查网络');
            console.error('获取家庭成员接口异常:', err);
          });
      }
    },
    
    // 根据家庭ID和姓名获取身份证号
    fetchIdCardByFamilyIdAndName() {
      if (this.familyForm.familyId && this.familyForm.headOfHousehold) {
        request.get(`/familyPayment/getIdCardByFamilyIdAndName`, {
          params: {
            familyId: this.familyForm.familyId,
            name: this.familyForm.headOfHousehold
          }
        })
          .then(res => {
            if (res.code === 200 && res.data) {
              this.formData.payerIdCard = res.data;
            } else {
              this.$message.warning('未找到对应身份证号，请手动输入');
              this.formData.payerIdCard = '';
            }
          })
          .catch(err => {
            this.$message.error('获取身份证号失败，请重试');
            console.error('获取身份证号接口异常:', err);
          });
      }
    },
    
    // 确认家庭及成员选择
    confirmFamilySelection() {
      if (!this.familyForm.familyId || !this.familyForm.headOfHousehold) {
        this.$message.warning("请选择家庭ID和户主");
        return;
      }
      
      // 确保户主在参合人员列表中
      if (!this.selectedNames.includes(this.familyForm.headOfHousehold)) {
        this.selectedNames.push(this.familyForm.headOfHousehold);
      }

      // 调用修改参合状态接口
      request.post("/familyPayment/updateCooperativeStatus", {
        familyId: this.familyForm.familyId,
        names: this.selectedNames
      })
      .then(res => {
        if (res.code === 200) {
          this.$message.success("参合状态更新成功");
          this.fetchCurrentYearFee(); // 查询年费标准
        } else {
          this.$message.error(res.message);
        }
      })
      .catch(err => {
        this.$message.error('更新参合状态失败，请重试');
        console.error('更新参合状态接口异常:', err);
      });
    },
    
    // 获取当前年度缴费标准
    fetchCurrentYearFee() {
      request.get("/familyPayment/getCurrentYearFeeAmount")
        .then(res => {
          if (res.code === 200) {
            this.feeAmount = res.data;
            // 计算缴费总额：选中人数 * 年费标准
            this.formData.totalAmount = this.selectedNames.length * this.feeAmount;
            
            // 填充表单数据
            this.dialogTitle = "新增缴费记录";
            this.dialogVisible = true; // 打开缴费信息弹窗
            this.familySelectVisible = false; // 关闭家庭选择弹窗
            
            // 填充家庭相关信息
            this.formData.familyId = this.familyForm.familyId;
            this.formData.payerName = this.familyForm.headOfHousehold; // 缴费人姓名设为户主
            this.formData.nameList = this.selectedNames; // 参合人员列表
            this.formData.year = new Date().getFullYear(); // 默认当前年份
            this.formData.paymentTime = formatDate(new Date(), "YYYY-MM-DD HH:mm:ss"); // 默认当前时间
          } else {
            this.$message.error("获取年费标准失败: " + res.message);
          }
        })
        .catch(err => {
          this.$message.error('获取年费标准失败，请重试');
          console.error('获取年费标准接口异常:', err);
        });
    },
    
    // 家庭选择弹窗关闭处理
    handleFamilySelectClose() {
      // 如果没有选择家庭和成员，重置相关数据
      if (!this.formData.familyId || !this.formData.payerName) {
        this.resetForm();
      }
    },
    
    // 编辑缴费记录
    handleEdit(row) {
      this.dialogTitle = '编辑缴费记录';
      this.formData = {
        ...row,
        paymentTime: row.paymentTime ? formatDate(row.paymentTime, 'YYYY-MM-DD HH:mm:ss') : ''
      };
      this.dialogVisible = true;
    },
    
    // 删除缴费记录
    handleDelete(row) {
      this.$confirm(`确认删除缴费记录「${row.payerName}-${row.year}年度」吗？该操作不可恢复`, '提示', {
        type: 'warning',
        confirmButtonText: '确认删除',
        cancelButtonText: '取消'
      })
        .then(() => {
          request.post(`/familyPayment/delete/${row.paymentId}`)
            .then(res => {
              if (res.code === 200) {
                this.$message.success('缴费记录删除成功');
                this.fetchData();
              } else {
                this.$message.error(res.message || '缴费记录删除失败');
              }
            })
            .catch(err => {
              this.$message.error('删除失败，请联系管理员');
              console.error('删除接口异常:', err);
            });
        })
        .catch(() => {});
    },
    
    // 提交表单
    submitForm() {
      this.$refs.formRef.validate(valid => {
        if (!valid) return;

        const isEdit = !!this.formData.paymentId;
        const apiUrl = isEdit ? '/familyPayment/update' : '/familyPayment/create';
        
        // 处理日期格式，转换为 ISO 8601 格式
        const formattedData = {
          ...this.formData,
          paymentTime: this.formData.paymentTime 
            ? new Date(this.formData.paymentTime).toISOString() 
            : null,
          totalAmount: this.formData.totalAmount?.toString()
        };

        request.post(apiUrl, formattedData)
          .then(res => {
            if (res.code === 200) {
              this.$message.success(`${this.dialogTitle}成功`);
              this.dialogVisible = false;
              this.fetchData();
            } else {
              this.$message.error(`${this.dialogTitle}失败: ${res.message}`);
            }
          })
          .catch(err => {
            console.error(`${this.dialogTitle}接口异常:`, err);
            this.$message.error(`${this.dialogTitle}失败，请检查参数或联系管理员`);
          });
      });
    },
    
    // 重置表单
    resetForm() {
      this.$refs.formRef?.resetFields();
      this.familyForm = { familyId: null, headOfHousehold: '' };
      this.familyMembers = [];
      this.selectedNames = [];
      this.feeAmount = null;
      this.formData = {
        paymentId: null,
        familyId: null,
        year: null,
        payerName: '',
        payerIdCard: '',
        totalAmount: null,
        paymentTime: null,
        operatorId: null,
        operatorName: '',
        invoiceNumber: '',
        paymentMethod: '',
        remark: '',
        nameList: []
      };
    }
  },
  
  created() {
    this.fetchData();
  }
};
</script>

<style scoped>
/* 基础容器样式 */
.payment-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

/* 搜索栏样式 */
.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f9fafc;
  border-radius: 6px;
  border: 1px solid #ebeef5;
}

/* 操作按钮样式 */
.operation-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

/* 表格样式 */
.table-container {
  overflow-x: auto;
}

.el-table {
  font-size: 14px;
  margin-top: 10px;
}

.el-table th {
  background-color: #f5f7fa;
  font-weight: 500;
  color: #333;
  text-align: center;
}

.el-table .cell {
  padding: 10px 8px;
  text-align: center;
}

/* 省略号样式 */
.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: block;
}

/* 对话框底部样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
  background-color: #f9fafc;
  border-radius: 0 0 6px 6px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .el-table-column:not([fixed]) {
    min-width: 120px;
  }
}
</style>    